<?php

/**
 * 发现搜索页
 * ============================================================================
 * $Author: 王海龙 $
 * $Id: index.php 2015-01-01 王海龙 $
*/

define('IS_MOBILE', true);
require(dirname(__FILE__) . '/../includes/init.php');
include_once(ROOT_PATH . '/includes/funTvd.php');
@ini_set('display_errors',        1);
/* 初始化赋值模板 */
assign_template();

$smarty->assign('page_title',      htmlspecialchars($_CFG['shop_title'])); // 首页页面标题
$smarty->assign('keywords',        htmlspecialchars($_CFG['shop_keywords'])); // 首页SEO网站关键词
$smarty->assign('description',     htmlspecialchars($_CFG['shop_desc'])); // 首页SEO网站描述


/* 查看是否有搜索记录 */
if (!empty($_SESSION['tvdSearchKeys'])) {
    $keyList = array_unique($_SESSION['tvdSearchKeys']);
}
elseif (!empty($_COOKIE['ECS']['tvdSearchKeys'])) {
    $keyList = array_unique(JSON()->decode($_COOKIE['ECS']['tvdSearchKeys']));
    $_SESSION['tvdSearchKeys'] = $keyList;
}
else {
    $keyList = array();
}
$keyList = array_slice(array_reverse($keyList), 0, 10);


/* 默认搜索页面（未输入内容） */
if (empty($_REQUEST['q']) && empty($_REQUEST['c'])) {
    $smarty->assign('keyList', $keyList);
    $smarty->display('tvd/search.dwt');
    exit;
}

/* AJAX返回搜索结果 */
if (!empty($_REQUEST['isAjax'])) {

    $tvdList = getTvdList();
    $smarty->assign('tvdList', $tvdList);
    if (!empty($tvdList)) {
        $result['error'] = 0;
        $result['count'] = count($tvdList);
        $result['content'] = $smarty->fetch('tvd/tvdList.lbi');
    } else {
        $result['error'] = 1;
        $result['message'] = '已全部加载！END';
    }
    echo JSON()->encode($result);
    exit();
}


/* 如果存在搜索词，记录为历史搜索 */
if (!empty($_REQUEST['q'])) {
    $keyList[] = trim($_REQUEST['q']);
    $_SESSION['tvdSearchKeys'] = $keyList;
    setcookie('ECS[tvdSearchKeys]',JSON()->encode($keyList),time()+3600*24*365);
}
/* 搜索词、品牌、分类 */
$q   = !empty($_REQUEST['q']) ? htmlspecialchars(trim($_REQUEST['q'])) : '';
$c   = !empty($_REQUEST['c']) ? intval($_REQUEST['c']) : 0;
$smarty->assign('c', $c);
$smarty->assign('q', $q);

/* 如果存在搜索分类，查询分类名称 */
if (!empty($c)) {
    $sql = "SELECT cat_name FROM egg_tvd_cat WHERE cat_id = '$c'";
    $smarty->assign('cname', DB()->getOne($sql));
}

if ((!isset($toUrl)||empty($toUrl)) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
{
    $toUrl = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'tvd_list.php') ? 'tvd_list.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
    $smarty->assign('toUrl', $toUrl);
}

$smarty->display('tvd/list.dwt');

